/* eslint-disable */
import { createElement, HTMLAttributes, useEffect, useMemo, useState, type FC } from 'react';
import classNames from 'classnames';
import dayjs from 'dayjs';
import localeData from 'dayjs/plugin/localeData';
import { calendarDefaultProps } from './defaultProps';
import type { CalendarOptions } from './type';
import CalendarCell from './CalendarCell';
import { createDateList, createMonthList, createYearList, rangeYears } from './_util';
import Popup from '../popup';
import 'dayjs/locale/zh-cn';
import numberToWord from '../_util/numberToWord';
import { WidthsNumber } from '../common';

dayjs.extend(localeData);

dayjs.locale('zh-cn');

export interface CalendarProps extends CalendarOptions, HTMLAttributes<HTMLDivElement> {}

const Calendar: FC<CalendarProps> = (props) => {
  const { className, ui, inline, firstDayOfWeek, format, mode, forwardedRef, ...calendarProps } = props;
  const [moded, setModed] = useState(mode!);
  const [year, setYear] = useState(dayjs().year());
  const [month, setMonth] = useState(dayjs().month() + 1);
  const [firstDayOfWeeked, setFirstDayOfWeeked] = useState(firstDayOfWeek!);
  const [formated, setFormated] = useState(format!);
  const [currentDate, setCurrentDate] = useState(dayjs(dayjs().format(formated)));
  const [weeksOrder, setWeeksOrder] = useState<Array<string>>();
  const [activeIndexs, setActiveIndexs] = useState<{ [key: string]: string }>();
  const [rowNum, setRowNum] = useState<WidthsNumber>(7);

  const wm = dayjs.weekdaysMin(true);

  useEffect(() => {
    setWeeksOrder(wm.slice(firstDayOfWeeked - 1).concat(wm.slice(0, firstDayOfWeeked - 1)));
  }, [firstDayOfWeeked]);

  useEffect(() => {
    const modeRowNum: { [key: string]: WidthsNumber } = {
      day: 7,
      month: 3,
      year: 3,
    };
    setRowNum(modeRowNum[moded]);
  }, [moded]);

  const dateList = useMemo(() => {
    if (moded === 'day') {
      return createDateList(year, month, firstDayOfWeeked, currentDate, formated!);
    } else if (moded === 'month') {
      return createMonthList(year, currentDate, formated, rowNum);
    } else if (moded === 'year') {
      return createYearList(year, currentDate, formated, rowNum);
    } else {
      return [];
    }
  }, [year, month, firstDayOfWeeked, currentDate, formated, moded, rowNum]);

  const prevClick = () => {
    switch (moded) {
      case 'day':
        if (month === 1) {
          setMonth(12);
          setYear(year - 1);
        } else {
          setMonth(month - 1);
        }
        break;
      case 'month':
        setYear(year - 1);
        break;
      case 'year':
        setYear(year - 10);
        break;
      default:
        break;
    }
  };

  const nextClick = () => {
    switch (moded) {
      case 'day':
        if (month === 12) {
          setMonth(1);
          setYear(year + 1);
        } else {
          setMonth(month + 1);
        }
        break;
      case 'month':
        setYear(year + 1);
        break;
      case 'year':
        setYear(year + 10);
        break;
      default:
        break;
    }
  };

  const changeModed = () => {
    if (moded === 'day') {
      setModed('month');
    } else if (moded === 'month') {
      setModed('year');
    } else {
      setModed('day');
    }
  };

  const calendarTable = (
    <div className="calendar" tabIndex={0}>
      <table
        className={classNames(
          'ui',
          'celled',
          'center',
          'aligned',
          'unstackable',
          'table',
          moded,
          numberToWord(rowNum),
          'column',
        )}
      >
        <thead>
          <tr>
            <th colSpan={rowNum}>
              <span className="link" onClick={changeModed}>
                {moded === 'day' && dayjs(`${year}-${month}`).format('MMMM YYYY')}
                {moded === 'month' && year}
                {moded === 'year' && rangeYears(year)}
              </span>
              <span className="prev link" onClick={prevClick}>
                <i className="chevron left icon" />
              </span>
              <span className="next link" onClick={nextClick}>
                <i className="chevron right icon" />
              </span>
            </th>
          </tr>
          {moded === 'day' && (
            <tr>
              {weeksOrder?.map((week, index) => (
                <th key={index}>{week}</th>
              ))}
            </tr>
          )}
        </thead>
        <tbody>
          {dateList.map((col, colIndex) => (
            <tr key={colIndex}>
              {col.map((row, rowIndex) => (
                <CalendarCell
                  key={rowIndex}
                  active={
                    activeIndexs &&
                    [
                      dayjs(row.date).format('YYYY-MM-DD'),
                      dayjs(row.date).format('YYYY-MM'),
                      dayjs(row.date).format('YYYY'),
                    ].includes(activeIndexs[moded])
                  }
                  onClick={() => {
                    if (moded === 'day' && row.belongTo === 0) {
                      setActiveIndexs({ ...activeIndexs, [moded]: dayjs(row.date).format('YYYY-MM-DD') });
                    } else if (moded === 'month') {
                      setActiveIndexs({ ...activeIndexs, [moded]: dayjs(row.date).format('YYYY-MM') });
                      setModed('day');
                    } else if (moded === 'year') {
                      // setYear(dayjs(row.date).get('year'));
                      setActiveIndexs({ ...activeIndexs, [moded]: dayjs(row.date).format('YYYY') });
                      setModed('month');
                    }
                  }}
                  {...row}
                />
              ))}
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );

  return createElement(
    'div',
    { ref: forwardedRef, className: classNames({ ui }, 'calendar', className), ...calendarProps },

    inline ? (
      calendarTable
    ) : (
      <div className="ui input left icon">
        <i className="calendar icon"></i>
        <Popup className="calendar" content={calendarTable} position="bottom-start" trigger="focus">
          <input type="text" placeholder="Date/Time" />
        </Popup>
      </div>
    ),
  );
};

Calendar.displayName = 'Calendar';
Calendar.defaultProps = calendarDefaultProps;

export default Calendar;
